﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Lk.WebTow.Authorize;
using Lk.WebTow.Common;
using Lk.WebTow.Common.Encrypt;
using Lk.WebTow.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace Lk.WebTow.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class LoginController : Controller
    {
        private readonly ApplicationDbContext dbContext;
        public LoginController(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
        public IActionResult Index()
        {
            var cookieAdmin = HttpContext.AuthenticateAsync(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme);
            cookieAdmin.Wait();

            var principal = cookieAdmin.Result.Principal;

            if (principal != null)
            {
                var adminName = principal.Claims.FirstOrDefault(s => s.Type == "AdminName")?.Value;
                var adminPwd = principal.Claims.FirstOrDefault(s => s.Type == "AdminPwd")?.Value;
                if (!string.IsNullOrWhiteSpace(adminName))
                {
                    string salt = GetSalt(adminName);
                    adminPwd = DESEncrypt.Decrypt(adminName, salt);

                    var user = GetUserInfoByNameAndPwd(adminName, adminPwd, true);
                    if (user != null && user.UserName == adminName && user.IsLock == 0)
                    {
                        HttpContext.Session.Set(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme, ByteConvertHelper.Object2Bytes(user));
                        if (string.IsNullOrWhiteSpace(UtilConfig.Configuration["Site:JumpPage"]))
                        {
                            return new RedirectResult(UtilConfig.Configuration["Site:JumpPage"]);
                        }
                        else
                        {
                            return new RedirectResult("~/admin/home/index");
                        }
                    }
                }
            }
            return View();
        }
        public IActionResult Login(string userName, string password, string rememberMe, string txtCode)
        {
            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                TempData["SessionLoseError"] = "用户名和密码不能为空";
                return RedirectToAction("Index");
            }
            var user = GetUserInfoByNameAndPwd(userName, password, true);
            if (user != null && user.UserName == userName && user.IsLock == 0)
            {
                HttpContext.Session.Set(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme, ByteConvertHelper.Object2Bytes(user));

                //sso
                string ssoServer = UtilConfig.Configuration["Site:sso:server"];
                if (string.IsNullOrWhiteSpace(ssoServer))
                {
                    var userClaims = new ClaimsPrincipal(
                        new ClaimsIdentity(new[] {
                            new Claim("AdminName",user.UserName),new Claim("AdminPwd",user.Password)
                        }, AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme)
                        );
                    HttpContext.SignInAsync(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme, userClaims, new AuthenticationProperties
                    {
                        ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromHours(1)),
                        IsPersistent = true,
                        AllowRefresh = false
                    });
                    string returnUrl = Request.Query["returnUrl"];
                    if (!string.IsNullOrWhiteSpace(returnUrl))
                    {
                        return new RedirectResult(returnUrl);
                    }
                    if (string.IsNullOrWhiteSpace(UtilConfig.Configuration["Site:JumpPage"]))
                    {
                        return new RedirectResult(UtilConfig.Configuration["Site:JumpPage"]);
                    }
                    else
                    {
                        return new RedirectResult("~/admin/home/index");
                    }
                }
                else
                {
                    return new RedirectResult("~/sso/registerSite");//sso 地址
                }
            }
            else if (user != null && user.UserName == userName && user.IsLock != 0)
            {

                TempData["SessionLoseError"] = "用户为授权,请联系管理员";
                return RedirectToAction("Index");
            }
            else
            {
                TempData["SessionLoseError"] = "用户名或密码不正确";
                return RedirectToAction("Index");
            }

        }
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme);
            return RedirectToAction("Index", "Login");

        }
        private NcManager GetUserInfoByNameAndPwd(string userName, string pwd, bool isEncrypt)
        {
            string excryType = UtilConfig.Configuration["Site:PwdEncryType"];
            switch (excryType)
            {
                case "MD5":
                    pwd = MD5Comm.Get16MD5One(pwd);
                    break;
                case "DES":
                    if (isEncrypt)
                    {
                        string salt = GetSalt(userName);
                        if (string.IsNullOrWhiteSpace(salt))
                        {
                            return null;
                        }
                        pwd = DESEncrypt.Encrypt(pwd, salt);
                    }
                    break;
            }
            return dbContext.NcManager.FirstOrDefault(s => s.UserName == userName && s.Password == pwd);
        }
        public string GetSalt(string userName)
        {
            var adminInfo = dbContext.NcManager.Where(s => s.UserName == userName).FirstOrDefault();
            return adminInfo != null ? adminInfo.Salt : string.Empty;
        }
        public ActionResult IllegalUser(string msg)
        {
            ViewBag.Msg = msg;
            return View();
        }
    }
}